package com.umeox.mediaplayer

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.text.format.DateUtils
import android.util.Log
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.SeekBar
import android.widget.TextView
import com.umeox.moto.watch.themes.app.ThemeAppCompatActivity
import com.yc.music.config.MusicConstant
import com.yc.music.inter.OnPlayerEventListener
import com.yc.music.model.AudioBean
import com.yc.music.tool.BaseAppHelper
import com.yc.music.utils.MusicSpUtils
import java.lang.StringBuilder
import java.util.*
import kotlin.math.abs


class MusicActivity : ThemeAppCompatActivity(), View.OnClickListener, OnPlayerEventListener {
    private var tvTitle: TextView? = null
    private var tvArtist: TextView? = null
    private var tvCurrentTime: TextView? = null
    private var sbProgress: SeekBar? = null
    private var tvTotalTime: TextView? = null
    private var ivPrev: com.umeox.moto.watch.themes.widget.ImageView? = null
    private var ivPlay: ImageView? = null
    private var ivNext: com.umeox.moto.watch.themes.widget.ImageView? = null
    private var ivPlayMode: ImageView? = null
    private var ivVolume: ImageView? = null
    private var mLastProgress = 0
    private var isDraggingProgress = false

    private lateinit var audioBean: AudioBean
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_music)
        MusicSpUtils.init(this.application)
        playModeLevel =
            MusicSpUtils.getInstance(MusicConstant.SP_NAME).getInt(MusicConstant.PLAY_MODE, 0)

        audioBean = intent.getSerializableExtra(KEY_URI_MUSIC) as AudioBean


        initView()
        initListener()
        window.decorView.post {
            val helper = BaseAppHelper.get()
            if (helper.playService.playingMusic != audioBean) {
                helper.playService.play(helper.musicList.indexOf(audioBean))
            }
            setViewData(audioBean)

        }
    }


    private fun initView() {
        tvTitle = findViewById(R.id.tv_title)
        tvArtist = findViewById(R.id.tv_artist)
        tvCurrentTime = findViewById(R.id.tv_current_time)
        sbProgress = findViewById(R.id.sb_progress)
        tvTotalTime = findViewById(R.id.tv_total_time)
        ivPrev = findViewById(R.id.iv_prev)
        ivPlay = findViewById(R.id.iv_play)
        ivNext = findViewById(R.id.iv_next)
        ivVolume = findViewById(R.id.iv_volume)
        ivPlayMode = findViewById(R.id.iv_play_mode)
        ivPlayMode?.setImageLevel(playModeLevel)

    }

    private fun initPlayServiceListener() {
        if (BaseAppHelper.get().musicService == null) {
            return
        }
        BaseAppHelper.get().musicService.addOnPlayEventListener(this);

    }

    private fun onChangeImpl(music: AudioBean?) {
        if (music == null) {
            return
        }
        tvTitle!!.text = music.title
        ivPlay!!.isSelected =
            BaseAppHelper.get().musicService.isPlaying || BaseAppHelper.get().musicService.isPreparing
        tvArtist!!.text = music.artist
        tvTotalTime!!.text = formatTime(music.duration)
        sbProgress!!.max = music.duration.toInt()
        sbProgress!!.progress = BaseAppHelper.get().musicService.currentPosition.toInt()
    }

    private fun initListener() {
        ivPlay!!.setOnClickListener(this)
        ivPrev!!.setOnClickListener(this)
        ivNext!!.setOnClickListener(this)
        ivVolume?.setOnClickListener(this)
        ivPlayMode?.setOnClickListener(this)
        findViewById<View>(R.id.iv_music_list)?.setOnClickListener(this)
        initSeekBarListener()
        initPlayServiceListener()
    }

    private fun initSeekBarListener() {
        val onSeekBarChangeListener: SeekBar.OnSeekBarChangeListener =
            object : SeekBar.OnSeekBarChangeListener {
                override fun onProgressChanged(seekBar: SeekBar, progress: Int, fromUser: Boolean) {
                    if (seekBar === sbProgress) {
                        if (abs(progress - mLastProgress) >= DateUtils.SECOND_IN_MILLIS) {
                            tvCurrentTime!!.text = formatTime(progress.toLong())
                            mLastProgress = progress
                        }
                    }
                }

                override fun onStartTrackingTouch(seekBar: SeekBar) {
                    if (seekBar === sbProgress) {
                        isDraggingProgress = true
                    }
                }

                /**
                 * 通知用户已结束触摸手势,触摸结束时调用
                 * @param seekBar               seekBar
                 */
                override fun onStopTrackingTouch(seekBar: SeekBar) {
                    if (seekBar === sbProgress) {
                        isDraggingProgress = false

                        if (BaseAppHelper.get().musicService.isPlaying || BaseAppHelper.get().musicService.isPausing) {
                            val progress = seekBar.progress
                            BaseAppHelper.get().musicService.seekTo(progress)
                        } else {
                            seekBar.progress = 0
                        }
                    }
                }
            }
        sbProgress!!.setOnSeekBarChangeListener(onSeekBarChangeListener)
    }

    var playModeLevel = 0
    override fun onClick(v: View) {
        when (v.id) {

            R.id.iv_play -> BaseAppHelper.get().musicService?.playPause()
            R.id.iv_next -> BaseAppHelper.get().musicService?.doNext()
            R.id.iv_prev -> BaseAppHelper.get().musicService?.doPrev()
            R.id.iv_volume -> startActivity(Intent(this, VolumeActivity::class.java))
            R.id.iv_music_list -> finish()
            R.id.iv_play_mode -> {
                playModeLevel++
                if (playModeLevel > 2) {
                    playModeLevel = 0
                }
                MusicSpUtils.getInstance(MusicConstant.SP_NAME)
                    .put(MusicConstant.PLAY_MODE, playModeLevel)
                ivPlayMode?.setImageLevel(playModeLevel)
            }

            else -> {}
        }
    }



    @SuppressLint("SetTextI18n")
    private fun setViewData(playingMusic: AudioBean) {

        tvTitle!!.text = playingMusic.title
        tvArtist!!.text = playingMusic.artist
        val musicService = BaseAppHelper.get().musicService
        sbProgress!!.progress = musicService.currentPosition.toInt()
        sbProgress!!.secondaryProgress = 0
        sbProgress!!.max = playingMusic.duration.toInt()
        mLastProgress = 0
        tvCurrentTime!!.text = "00:00"
        tvTotalTime!!.text = formatTime(playingMusic.duration)
        setCoverAndBg(playingMusic)
        val playing = musicService.isPlaying
        ivPlay!!.isSelected = playing || musicService.isPreparing
    }

    private fun setCoverAndBg(music: AudioBean) {
        /*      //mAlbumCoverView.setCoverBitmap(CoverLoader.getInstance().loadRound(music));
              ivPlayPageBg.setImageBitmap(CoverLoader.getInstance().loadBlur(music));*/
    }

    fun formatTime(milliseconds: Long): String? {
        if (milliseconds <= 0 || milliseconds >= 24 * 60 * 60 * 1000) {
            return "00:00"
        }
        val totalSeconds = milliseconds / 1000
        val seconds = totalSeconds % 60
        val minutes = totalSeconds / 60 % 60
        val hours = totalSeconds / 3600
        val stringBuilder = StringBuilder()
        val mFormatter = Formatter(stringBuilder, Locale.ENGLISH)
        return if (hours > 0) {
            mFormatter.format("%d:%02d:%02d", hours, minutes, seconds).toString()
        } else {
            mFormatter.format("%02d:%02d", minutes, seconds).toString()
        }
    }


    override fun onChange(music: AudioBean) {
        onChangeImpl(music)
    }

    override fun onPlayerStart() {
        ivPlay!!.isSelected = true
    }

    override fun onPlayerPause() {
        ivPlay!!.isSelected = false
    }

    override fun onCompletion() {
    }

    override fun onUpdateProgress(progress: Int) {
        sbProgress!!.progress = progress
    }

    override fun onBufferingUpdate(percent: Int) {
//        sbProgress?.secondaryProgress = sbProgress?.max?.toLong()?.times((percent.toLong() / 100F))?.toInt()!!
    }

    override fun onTimer(remain: Long) {
    }

    override fun onDuration(totalDuration: Int) {
//        sbProgress!!.max = totalDuration
//        tvTotalTime!!.text = formatTime(totalDuration.toLong())

    }

    override fun onDestroy() {
        super.onDestroy()
        BaseAppHelper.get().musicService?.removeOnPlayEventListener(this)
    }
}